package com.naiterui.ehp.bp.support.exception;

import com.naiterui.ehp.bp.security.exception.AuthenticationException;
import com.naiterui.ehp.bp.security.exception.BadRequestException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 王泽浩
 * @date 2020/7/21 11:11 上午
 * @since 1.0.0
 */
@Slf4j
@Order(value = Integer.MIN_VALUE)
@ControllerAdvice
@ConditionalOnClass({AuthenticationException.class})
public class SecurityexceptionHandler extends BaseGlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler({AccessDeniedException.class})
    public ResponseEntity<ResponseVO<Object>> handleBusinessException(AccessDeniedException e, HttpServletRequest request) {
        return this.getResponseEntity(request, e, BaseExceptionCodes.ILLEGAL_REQUEST, e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler({AuthenticationException.class})
    public ResponseEntity<ResponseVO<Object>> handleAuthenticationException(AuthenticationException e, HttpServletRequest request) {
        return this.getResponseEntity(request, e, BaseExceptionCodes.ILLEGAL_REQUEST, e.getMessage(), e.getData());
    }

    @ResponseBody
    @ExceptionHandler({BadCredentialsException.class})
    public ResponseEntity<ResponseVO<Object>> handleBadCredentialsException(BadCredentialsException e, HttpServletRequest request) {
        return this.getResponseEntity(request, e, BaseExceptionCodes.LOGIN_DOC_FAIL, e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler({DisabledException.class})
    public ResponseEntity<ResponseVO<Object>> handleDisabledException(DisabledException e, HttpServletRequest request) {
        return this.getResponseEntity(request, e, BaseExceptionCodes.FAILED, e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler({BadRequestException.class})
    public ResponseEntity<ResponseVO<Object>> handleBadRequestException(BadRequestException e, HttpServletRequest request) {
        return this.getResponseEntity(request, e, BaseExceptionCodes.ILLEGAL_REQUEST, e.getMessage(), null);
    }

}
